// packageI/redeem_code/index/index.js
const skinBehavior = require("../../../utils/themeSkin/skinBehavior")
const app = getApp()
var specsManage = []; // 选择池 用于排序
var optionsId = ""; // 选择后的 规格ID
Page({

  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    host: app.data.host,
    radioChoose:"",
    showChoose: false,
    dispatch_types: [],
    has_many_goods: [],
    goodsDescription: "",
    show: false,
    share: 0,
    language: "",
    list: [],
    carts: [],
    details: {},
    Height: '',
    nums: 0,
    index_goods: 0, //当前商品索引
    activity_gid: "",
    current_page: 1,
    last_page: 1,

    goodsPopupShow: false,
    specsShow: false,
    hand_goods_obj: {},
    carList: [],
    hand_goods_id: "",
    message_card: "",

    showKefu: false,
    customer_open: "",
    cservice: "",
    service_mobile: "",
    service_QRcode: "",

    popThumb: "",
    popTitle: "",
    popNum: 0,
    popPrice: "",
    show2: false,
    goodsInfo: {},
    specid: "",
    has_many_options: [],
    current_index: 0,

    code_id: "", //兑换码id
    id: "", //兑换码记录id
    code_sn: "", //序列号
    face_price:"",//礼品卡面值
    record_id:"",//礼品卡-卡密ID
    option_type: "",//操作类型
    mid:"",//转赠用户id
    card_status:"",//礼品卡状态
    goodsId:"",//激活卡对应的商品id,
    store_id: 0,
    gift_card_record_id: '',
    selectedGoodsId: 0,
    inputCodeSn: '',
    isScan: false,
    isChecked: false,
    loadingShow: false,
    loadingText: '加载中...'
  },

  /**
   * 生命周期函数--监听页面加载
   * op:操作  1：激活 2:绑定 3:兑换 4:转赠 
   */
  onLoad: function (options) {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en,
      code_id: options.code_id || '',
      code_sn: options.code_sn || '',
      face_price: options.face_value || '',
      record_id: options.record_id || '',
      option_type: options.option_type || '',
      mid: options.mid || '',
      isChecked: options.isChecked || false
    })
    if (options.share) {
      this.setData({
        share: options.share
      })
    }

    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        // 隐藏主页图标
        // 隐藏底部导航
        // 显示【订单】按钮
        this.setData({isScan: true})
        wx.hideHomeButton()

        var info_arr = [];
        info_arr = scene.split("&");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == 'o') {
            this.setData({
              option_type:chil_arr[1]
            })
          }
          if (chil_arr[0] == 'id') {
            this.setData({
              record_id:chil_arr[1]
            })
          }
          if (chil_arr[0] == 'c') {
            this.setData({
              code_id:chil_arr[1]
            })
          }
        }
      }
    }
  },

  video_handle() {
    app.tips("兑换数量最多为1")
  },
  share_handle() {
    this.onShareAppMessage()
  },
  Hidden_overlay() {
    this.setData({
      show: false
    })
  },
  change(e) {
    this.setData({
      code_sn: e.detail.value
    })
  },
  
  getCardStatus(recordId) {
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.record.info'),
      data: {
        record_id:recordId,
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 1 ){
          this.setData({
            card_status:data.status,
            code_sn:data.code_sn,
            goodsId:data.goods_id,
            gift_card_record_id: data.id
          })
        } else{
          app.tips(msg);
        }
        this.getData()
      }
    })
  },
  binding_handle_donation() {
    const _this = this
    wx.showModal({
      title: '提示',
      content: `确认绑定礼品卡，绑定到您的账户后将无法做解绑操作。面值：${this.data.face_price}元`,
      complete: (resC) => {
        if (resC.confirm) {
          app._getNetWork({
            url: app.getNetAddresss('plugin.gift-card.api.record.tranferBind'),
            data: {
              mid: _this.data.mid,
              code_sn:_this.data.code_sn,
              record_id:_this.data.record_id,
            },
            success: resdata => {
              let {
                result,
                msg,
                data
              } = resdata.data;
              if (result == 1 ){
                _this.setData({
                  code_sn:data.code_sn,
                  code_id:data.code_id,
                  face_price:data.face_value,
                  option_type: ''
                })
                _this.getData();
              } 
              app.tips(msg);
            }
          })
        }
      }
    })
  },
  
  /**
   * 输入卡密
   * @param {Object} e 
   */
  codeSnInput: function(e) {
    const { detail } = e
    this.setData({ inputCodeSn: detail })
  },
  binding_handle() {
    const _this = this
    console.log(_this.data.details.status)
    if (_this.data.details.type == 1 && !_this.data.inputCodeSn) {
      app.tips('请输入密码！')
      return
    }
    const code_sn = _this.data.details.type == 2 ? _this.data.code_sn : _this.data.inputCodeSn
    wx.showModal({
      title: '提示',
      content: `确认绑定礼品卡，绑定到您的账户后将无法做解绑操作。面值：${this.data.details.face_value}元`,
      confirmText: '确认绑定',
      complete: (res) => {
        if (res.confirm) {
          app._getNetWork({
            url: app.getNetAddresss('plugin.gift-card.api.record.bind'),
            data: {
              code_sn,
              code_num: this.data.details.code_num
            },
            success: resdata => {
              let {
                result,
                msg,
                data
              } = resdata.data;
              app.tips(msg);
              if (result) {
                // 全场通用卡绑定
                // if (_this.data.details.usage == 1) {
                //   setTimeout(() => {
                //     wx.redirectTo({
                //       url: '/packageG/pages/category_v2/category_v2',
                //     })
                //   }, 1500);
                // } else {
                  // 指定商品卡绑定
                  _this.setData({
                    code_id: data.code_id,
                    code_sn: data.code_sn
                  })
                  _this.getData();
                // }
              }
            }
          })
        }
      }
    })
  },
  getData() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.list.info'),
      data: {
        id: this.data.code_id,
        code_sn: this.data.code_sn,
        scope: 'pass'
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        console.log('getData::', data)
        if (result == 0) {
          return app.tips(msg);
        }
        this.setData({
          details: data,
          customer_open: data.cservice.customer_open,
          cservice: data.cservice.cservice,
          service_mobile: data.cservice.service_mobile,
          service_QRcode: data.cservice.service_QRcode,
          card_status: data.status,
          face_price: data.face_value,
          store_id: data.store_id
        })
        if (data.login_status == 0) {
          this.setData({
            show: true
          })
          return;
        }
        if (this.data.share == 1) {
          this.setData({
            show: true
          });

        }

        if (data.usage == 2) { //  || data.usage == 1
          this.getGoods({
            id: data.id
          })
          this.setData({
            code_sn: data.current_code || this.data.code_sn
          })
        }
      }
    })
  },
  getGoods(json = {}) {
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.list.goodList'),
      data: json,
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          app.tips(msg);
          return
        }
        this.setData({
          list: data || []
        });
        return
        this.setData({
          current_page: data.current_page,
          last_page: data.last_page
        })
        if (data.current_page == 1) {
          this.data.list = data.data.forEach(item => {
            item.count = 0;
          })
          this.setData({
            list: data.data || []
          });
          if (data.data && data.data.length <= 5) {
            this.setData({
              Height: 'auto'
            })
          }
        } else {
          data.data.forEach(item => {
            item.count = 0
          })
          let arr = data.data;

          let list = this.data.list.concat(arr);
          this.setData({
            list
          })
        }

      }
    })
  },
  getMoreData() {
    if (this.data.current_page >= this.data.last_page) {
      return;
    }
    this.getGoods({
      page: this.data.current_page + 1,
      id: this.data.code_id
    })

  },
  login() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  to_list() {
    wx.navigateTo({
      url: '/packageG/gift_card/center/center',
    })
  },
  severShowTap() {
    this.setData({
      showKefu: true
    })
  },
  activate() {

    wx.navigateTo({
      url: '/packageG/gift_card/goods/goods?goods_id=' + this.data.goodsId +"&option_type=1"+ "&record_id="+this.data.record_id + '&gift_card_record_id=' + this.data.gift_card_record_id
    });
  },

  /**
   * 全场通用礼品卡兑换成积分
   */
  redeemIntegral: function() {
    const { record_id } = this.data.details
    const urlStr = app.getNetAddresss('plugin.gift-card.api.record.integralExchange')
    const _this = this
    wx.showLoading({
      title: '加载中...',
    })
    app._postNetWork({
      url: urlStr,
      data: { id: record_id },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: resData.msg,
            confirmText: '去使用',
            complete: (resC) => {
              if (resC.cancel) {
                _this.getData()
              }
              if (resC.confirm) {
                const { store_id } = _this.data
                const url = store_id ? `/packageC/o2o/o2oStore/o2oStore?store_id=${store_id}` : '/packageG/pages/category_v2/category_v2'
                wx.navigateTo({ url })
              }
            }
          })
        } else {
          app.tips(resData.msg || '兑换失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  check() {
    let arr = [],
      plugins_ids = [];
    const { selectedGoodsId, list } = this.data
    if (!selectedGoodsId) {
      app.tips('请选择要兑换的商品')
      return
    }
    const goods = list.find(item => item.id == selectedGoodsId)
    if (goods) {
      let goodsInfo = {
        goods_id: selectedGoodsId,
        total: 1
      }
      if (goods.has_option) {
        goodsInfo.option_id = goods.has_many_options[0]
        goods.has_many_options.forEach(item => {
          arr.push({
            goods_id: selectedGoodsId,
            total: 1,
            option_id: item.id
          })
        })
      } else {
        // 无规格
        arr.push({
          goods_id: selectedGoodsId,
          total: 1
        })
      }
    } else {
      app.tips('商品有误！')
      return
    }
    
    // this.data.list.forEach(item => {
    //   // if (item.count >= 1) {
    //   //   // let option_id = "0";
    //   //   if (item.has_option !== 1) {
    //   //     arr.push({
    //   //       goods_id: item.id,
    //   //       total: item.count,
    //   //       option_id: item.option_id
    //   //     })
    //   //   }

    //   //   if (!plugins_ids.includes(item.plugin_id)) {
    //   //     plugins_ids.push(item.plugin_id)
    //   //   }
    //   // }
    //   if (item.has_option) {
    //     // 含规格
    //     item.has_many_options.forEach(child => {
    //       arr.push({
    //         goods_id: item.id,
    //         total: 1,
    //         option_id: child.id
    //       })
    //     })
    //   } else {
    //     //不含规格的
    //     arr.push({
    //       goods_id: item.id,
    //       total: 1,
    //     })
    //   }

    // })
    // if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
    //   this.data.has_many_goods.forEach(item => {
    //     if (item.total >= 1) {
    //       arr.push({
    //         goods_id: item.goods_id,
    //         total: item.total,
    //         option_id: item.option_id
    //       })
    //     }
    //   })
    // }

    let ids = [];
    ids = arr.map(item => {
      return item.goods_id
    })
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.record.exchangeCheck'),
      data: {
        code_sn: this.data.code_sn,
        goods: JSON.stringify(arr)
      },
      success: resdata => {
        let {
          result,
          msg,data
        } = resdata.data;
        if (result) {
          this.toOder(ids, arr, plugins_ids)
        } else {
          if (data && data.length !== 0) {
            if (data.need_choose == 1) {
              this.setData({
                showChoose: true,
                dispatch_types: data.dispatch_types
              })
            } else {
              this.submitGoods();
            }
          } else {
            app.tips(msg)
          }
        }
      }
    })
  },
  closeChoose() {
    this.setData({
      showChoose: false
    })
  },
  toBuy() {
    this.submitGoods();
  },
  typeChange(event) {
    this.setData({
      radioChoose: Number(event.detail),
    });
  },
  // 提交订单
  submitGoods() {
    let goodsId = [],goods=[];
    if (this.data.showChoose && !this.data.radioChoose.toString()) {
      wx.showToast({
        icon: "none",
        title: "请先选择配送方式",
        duration: 1500,
      });
      return;
    }

    if (this.data.showChoose) {
      // 配送方式有冲突
      for (let i = 0; i < this.data.dispatch_types[this.data.radioChoose].member_carts.length; i++) {
        goodsId.push(
          this.data.dispatch_types[this.data.radioChoose].member_carts[i].goods_id
        );
        goods.push({
          total:this.data.dispatch_types[this.data.radioChoose].member_carts[i].total,
          goods_id:this.data.dispatch_types[this.data.radioChoose].member_carts[i].goods_id,
          option_id:this.data.dispatch_types[this.data.radioChoose].member_carts[i].option_id,
        })
      }
    }
    goodsId = goodsId.join(",")
    goods = JSON.stringify(goods)

    this.toOder(goodsId, goods, "")
    // app._getNetWork({
    //   url: app.getNetAddresss('plugin.gift-card.api.log.create'),
    //   data: {
    //     code_sn: this.data.code_sn
    //   },
    //   success: resdata => {
    //     let {
    //       result,
    //       msg,
    //       data
    //     } = resdata.data;
    //     if (result == 0) {
    //       return app.tips(msg);
    //     }

        
    //     let url_params = `tag=exchange_code&goodsId=${goodsId}&goods=${goods}&current_code=${this.data.details.code}&name=${this.data.details.name}&exchange_code_id=${data.exchange_code_id}`

    //     console.log("navigateTo url : ",`/packageD/buy/myOrder_v2/myOrder_v2?${url_params}` )
    //     wx.navigateTo({
    //       url: `/packageD/buy/myOrder_v2/myOrder_v2?${url_params}`
    //     });
    //   }

    // })



  },
  // 界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let id = 0;

    if (str == "first") {
      data = e;
      id = e.id;
    } else {
      data = e.target.dataset.item || e.currentTarget.dataset.item;

      id = e.target.dataset.id || e.currentTarget.dataset.id;
    }

    // 处理选择池
    this.manageSpecs(data);

    // 处理规格组合选择状态
    this.setGoodsSpecs(data);

    // 设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo(id);

  },

  // 处理选择池
  manageSpecs(data) {
    var specsObject = {};
    specsObject.id = data.id;
    specsObject.specid = data.specid;
    specsObject.title = data.title;

    if (specsManage.length > 0) {
      for (let i = 0; i < specsManage.length; i++) {
        if (specsManage[i].specid == specsObject.specid) {
          specsManage.splice(i, 1);
        }
      }
      specsManage.push(specsObject);
    } else {
      specsManage.push(specsObject);
    }

    // 排序
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
            newSpecsManage.push(specsManage[j]);
            break;
          }
        }
      }
      specsManage = newSpecsManage;
    }
    this.setGoodsDescription();
  },

  // 处理goodsDescription 数据
  setGoodsDescription() {
    var description = "";
    // 相等代表全选了 体现语句
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      description = "已选择 ";
      for (let i = 0; i < specsManage.length; i++) {
        description += specsManage[i].title + " ";
      }
      this.setData({
        goodsDescription: description,
      });
    } else {
      description = "请选择 ";

      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
            description += this.data.goodsInfo.has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description,
      });
    }
  },

  // 处理规格组合选择状态 过滤数据
  setGoodsSpecs(specs) {
    for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
      if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
        this.setGoodsSpecsStatus(this.data.goodsInfo.has_many_specs[i].specitem, specs.id);
      }
    }
  },

  // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    let options = []; // 数据池

    for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
      let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
      // 判断是否包含
      for (let j = 0; j < _specs.length; j++) {
        if (_specs[j] == id) {
          options.push(this.data.goodsInfo.has_many_options[i]);
        }
      }
    }

    for (let m = 0; m < options.length; m++) {
      let _specs = options[m].specs.split("_");
      for (let y = 0; y < _specs.length; y++) {
        if (_specs[y] != id && options[m].stock == 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = true;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = false;
            }
          }
        }
      }
    }
  },

  // 设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo(id) {
    let popPrice = "";
    // 根据ID 排序 specsManage.sort()
    specsManage.sort(function (a, b) {
      return a.id - b.id;
    });
    if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"
      this.setData({
        specid: goodsSpecs,
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
          } else {
            popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
          }
          console.log(popPrice, "popPrice-434");
          this.setData({
            popPrice: popPrice, // 设置价格
          });


          let popThumb = app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
          this.setData({
            popThumb,
          });

          optionsId = this.data.goodsInfo.has_many_options[i].id; // 设置规格ID，用于生成订单
          break;
        }
      }

    } else {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      this.setData({
        specid: goodsSpecs,
      });
    }

    let _goods = this.data.has_many_goods.filter(item => item.option_id == optionsId)
    console.log(optionsId, "optionsId====");
    console.log(_goods, "_goods===-501");
    if (_goods.length == 0) {
      this.setData({
        popNum: 0
      })
    } else {
      this.setData({
        popNum: _goods[0].total
      })
    }

  },

  // 处理商品goodsSpecs 并排序 新方法
  setGoodsSpecsBySort(specs) {
    let _specs = specs.split("_"); // 先变成数组
    // _specs.sort();//排序
    _specs.sort(function (a, b) {
      return a - b;
    });

    // 在组装回去
    let goodsSpecs = "";
    for (let j = 0; j < _specs.length; j++) {
      goodsSpecs += _specs[j] + "_";
    }
    goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"

    return goodsSpecs;
  },
  toOder(goodsId, arr, plugins_ids) {
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.log.create'),
      data: {
        code_sn: this.data.code_sn
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result == 0) {
          return app.tips(msg);
        }
        let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?&tag=giftcard_code&giftcard_code_id=${data.giftcard_code_id}&giftcard_price=${this.data.face_price}&id=${this.data.record_id}&goodsId=${goodsId}&goods=${JSON.stringify(arr)}`;
        if(this.data.details.show_info==1){
          urlStr+='&current_code='+this.data.details.code+'&name='+this.data.details.name
        }
        wx.navigateTo({
          url: urlStr
        });
      }
    })
  },
  // 商品数量
  goods_total() {
    let total = 0;
    this.data.list.forEach(item => {
      if (item.count >= 1) {
        total += item.count;
      }
    })
    return total;
  },
  redeem() {
      const { card_status, option_type, isChecked } = this.data
      const { usage, type, status } = this.data.details
      if (type == 1 && usage == 2 && status == 2 && !isChecked) {
        // 已激活指定商品的实体卡未查验
        this.checkCodeSn()
        return
      } else if (type == 1 && usage == 2 && status == 2 && isChecked) {
        // 已激活指定商品的实体卡已查验
        this.bindExchange()
        return
      }
      // 分享来的页面
      else if (option_type == 4) {
        this.binding_handle_donation()
        return
      } else if (usage == 2 && status == 4) {
        wx.navigateTo({
          url: '/packageA/member/myOrder_v2/myOrder_v2',
        })
        return
      }
      if (card_status == 1) {
        this.activate()
      }else if (card_status == 2){
        this.binding_handle()
      } else if (card_status == 3) {
        if (usage == 1) {
          // 全场通用
          this.redeemIntegral()
        } else if (usage == 2) {
          // 指定商品
          this.check()
        }
      }
  },

  /**
   * 指定商品实体卡查验卡片
   */
  checkCodeSn: function() {
    const { inputCodeSn, details } = this.data
    const { record_id } = details
    if (!inputCodeSn) {
      app.tips('请输入密码！')
      return
    }
    const _this = this
    wx.showLoading({ title: '加载中...' })
    app._getNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.record.checkCodeSn'),
      data: {
        code_id: record_id,
        code_sn: inputCodeSn
      },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ isChecked: true })
        } else {
          app.tips(resData.msg || '查验失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 指定商品实体卡绑定&兑换
   */
  bindExchange: function() {
    let arr = []
    const { selectedGoodsId, list } = this.data
    if (!selectedGoodsId) {
      app.tips('请选择要兑换的商品')
      return
    }
    const goods = list.find(item => item.id == selectedGoodsId)
    if (goods) {
      let goodsInfo = {
        goods_id: selectedGoodsId,
        total: 1
      }
      if (goods.has_option) {
        goodsInfo.option_id = goods.has_many_options[0]
        goods.has_many_options.forEach(item => {
          arr.push({
            goods_id: selectedGoodsId,
            total: 1,
            option_id: item.id
          })
        })
      } else {
        // 无规格
        arr.push({
          goods_id: selectedGoodsId,
          total: 1
        })
      }
    } else {
      app.tips('商品有误！')
      return
    }
    const { code_sn, face_price, record_id, details } = this.data
    this.setData({ loadingShow: true })
    const _this = this
    const goodsId = arr.map(item => {
      return item.goods_id
    })
    app._postNetWork({
      url: app.getNetAddresss('plugin.gift-card.api.record.automatedRedemption'),
      data: {
        goods: JSON.stringify(arr),
        code_sn: code_sn,
        code_num: details.code_num
      },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?&tag=giftcard_code&giftcard_code_id=${resData.data.giftcard_code_id}&giftcard_price=${face_price}&id=${record_id}&goodsId=${goodsId}&goods=${JSON.stringify(arr)}`;
          if(details.show_info==1){
            urlStr+='&current_code='+details.code+'&name='+details.name
          }
          wx.navigateTo({
            url: urlStr
          });
        } else {
          app.tips(resData.msg || '兑换失败！')
        }
      },
      complete: function() {
        _this.setData({ loadingShow: false })
      }
    })
  },

  /**
   * 商品选中
   * @param {Object} e 
   */
  goodsChange: function(e) {
    const { id } = e.currentTarget.dataset
    this.setData({ selectedGoodsId: id })
    console.log(this.data.selectedGoodsId)
  },

  openGoodsDetail(e) {
    if(this.data.details.show_detail==0){
      return;
    }
    let item = e.currentTarget.dataset.item;
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        goodsPopupShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "goodsDetails");
    }
    this.setData({
      index_goods: e.currentTarget.dataset.i,
      activity_gid:item.id,
    })
  },
  goodsDetailCartAdd(evt) {
    console.log(evt,"===>>>>>>");
    this.data.list.forEach(item => {
      if(item.id == this.data.activity_gid){
        if(item.has_option == 1){
          let json = {
            currentTarget:{
              dataset:{

              }
            }
          }
          this.selectOption(item.id,i,item)
          this.setData({
            goodsPopupShow: false,
            specsShow: false,
          });
        }else{
          this.setData({
            goodsPopupShow: false,
            specsShow: true,
          });
        }
      }
    })

  },
  getGoodsDetails(id, type) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(id)
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let name = "";
        if (type == "goodsDetails") {
          name = "goodsPopupShow";
        } else if (type == "specs") {
          name = "specsShow";
        }

        this.setData({
          [name]: true,
          hand_goods_obj: res.data.get_goods,
        });
      },
    });
  },
  submitAction() {
    // if (this.data.nums + 1 > this.data.details.exchange_limit) {
    //   app.tips("选择的数量已经超过兑换数量限制！") // ，请取消后再重新选择
    //   return
    // }
    if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
      // 请选择规格
      this.setData({
        show2: false,
      });
      wx.showToast({
        title: this.data.goodsDescription,
        icon: "none",
      });
      return;
    }
    let count = this.data.popNum + 1;
    this.data.has_many_goods.push({
      option_id: optionsId,
      goods_id: this.data.list[this.data.current_index].id,
      total: 1
    })
    if (this.data.details.single_order == 1) { //单选
      if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
        let has_many_goods = this.data.has_many_goods.filter(item => {
          if (item.goods_id == this.data.list[this.data.current_index].id) {
            return item;
          }
        })
        this.data.has_many_goods = has_many_goods
      }
      this.data.list.forEach(item => {
        if (item.id !== this.data.list[this.data.current_index].id) {
          item.count = 0;
        }
      })
    } else {
      this.data.list.forEach(item => {
        if (item.id === this.data.list[this.data.current_index].id) {
          item.count = 1;
        }
      })
    }

    console.log(this.data.has_many_goods, "this.data.has_many_goods");
    this.setData({
      has_many_goods: this.data.has_many_goods,
      list: this.data.list,
      popNum: count
    })


    this.updateNums()
  },
  updateNums() {
    let nums1 = 0;
    if (this.data.has_many_goods && this.data.has_many_goods.length !== 0) {
      this.data.has_many_goods.forEach(item => {
        if (item.goods_id == this.data.list[this.data.current_index].id) {
          nums1 += item.total
        }
      })
      this.data.list[this.data.current_index].count = nums1;
    }

    let nums = 0;
    this.data.list.forEach(item => {
      nums += item.count
    })
    this.setData({
      nums,
      list: this.data.list
    })
  },
  close() {
    this.setData({
      show2: false
    })
  },

  close_yz_specs_popup(e) {
    if (e.detail.clicktype == 1) {

      this.data.carts.forEach(item => {
        if (item.id == this.data.activity_gid) {
          item.total = e.detail.goodsCount
          item.option_id = e.detail.optionsId
        } else {
          item.total = 0;
          item.option_id = '0';
        }
      })
      this.data.list.forEach((item, index) => {
        if (item.id == this.data.activity_gid) {
          item.option_id = e.detail.optionsId
        } else if (item.has_option == 0) {
          item.option_id = '0';
        }
        if (this.data.details.single_order == 1) { //单选
          if (item.id == this.data.activity_gid) {
            this.data.list[index].count = e.detail.goodsCount;
          } else {
            this.data.list[index].count = 0;
          }
        } else { //多选
          if (item.id == this.data.activity_gid) {
            this.data.list[index].count = e.detail.goodsCount;
          }
        }
      })


      let nums = 0;
      this.data.list.forEach(item_2 => {
        nums += item_2.count
      })



      this.setData({
        specsShow: false,
        nums,
        list: this.data.list,
        carts: this.data.carts
      });

    } else {
      this.setData({
        specsShow: false,
      });
    }
  },
  // 多规格购物车
  selectOption(e) {
    console.log(e);
    optionsId = "";
    specsManage = [];
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    this.setData({
      specid: '',
      current_index: index,
      activity_gid: item.id,
      popTitle: item.title,
      popPrice: item.price,
      popThumb: item.thumb,
      show2: true,
      popNum: 0,
    })

    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(item.id)
      },
      success: resdata => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          goodsInfo: res.data.get_goods,
          has_many_options: this.data.has_many_options.concat(res.data.get_goods.has_many_options)
        });
        if (!this.data.specid.length) {
          let popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.min_point + "-" + this.data.goodsInfo.point_goods.max_point; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        let goodsDescription;
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          goodsDescription = this.data.goodsDescription;
          goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
        }
        this.setData({
          goodsDescription,
        });

        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            if (this.data.goodsInfo.goods_option_ids && this.data.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.data.goodsInfo.has_many_specs[i].specitem.length; j++) {
                if (this.data.goodsInfo.has_many_specs[i].specitem[j].id == Number(this.data.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[j], "first", i);
                }
              }
            } else {
              this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
            }
          }
        }

      }
    })
    // this.showGoodPup(item.id, true, item, index);
  },
  showGoodPup(_id, status, _item, i) {
    if (this.data.carts && this.data.carts.length !== 0) {
      this.data.carts.forEach(item => {
        if (item.id !== _id) {
          this.data.carts.push({
            ..._item,
            total: this.data.list[i].count,
            goods_id: _item.id
          });
        }
      })
      this.setData({
        carts: this.data.carts
      })
    } else {
      this.data.carts.push({
        ..._item,
        total: this.data.list[i].count,
        goods_id: _item.id
      });
      this.setData({
        carts: this.data.carts
      })
    }
    this.setData({
      activity_gid: _id,
      index_goods: i
    })

    if (_id == this.data.hand_goods_id) {
      this.setData({
        specsShow: true,
      });
    } else {
      this.data.hand_goods_id = _id;
      this.getGoodsDetails(_id, "specs");
    }
  },
  changeAddCount(e) {
    let index = e.currentTarget.dataset.i;
    console.log(index)
    let popNum = 0;
    if (index == 1) {
      // if (this.data.nums + 1 > this.data.details.exchange_limit) {
      //   app.tips("选择的数量已经超过兑换数量限制！") // ，请取消后再重新选择
      //   return
      // }
      popNum = this.data.popNum + 1;
      this.data.has_many_goods.forEach(item => {
        if (item.option_id == optionsId) {
          item.total = popNum;
        }
      })
    } else {
      if (this.data.popNum == 0) {
        this.data.has_many_goods.forEach(item => {
          if (item.option_id == optionsId) {
            item.total = 0
          }
        })
      } else {
        popNum = this.data.popNum - 1;
        this.data.has_many_goods.forEach(item => {
          if (item.option_id == optionsId) {
            item.total = popNum
          }
        })
      }
    }
    this.setData({
      popNum,
      list: this.data.list,
      has_many_goods: this.data.has_many_goods
    })
    this.updateNums();

  },
  reduceCartNum(e) {
    // if (this.data.nums + 1 > this.data.details.exchange_limit) {
    //   app.tips("选择的数量已经超过兑换数量限制！") // ，请取消后再重新选择
    //   return
    // }
    let cartid = e.currentTarget.dataset.cartid;
    this.data.list.forEach((chi, index) => {
      if (chi.id == cartid) {
        if (chi.count == 1) {
          this.data.list[index].count = 0;
        } else {
          this.data.list[index].count -= 1;
        }
      }
    })
    this.setData({
      list: this.data.list,
      nums: this.data.nums - 1
    })


  },
  addCartNum(e) {
    // if (this.data.nums + 1 > this.data.details.exchange_limit) {
    //   app.tips("选择的数量已经超过兑换数量限制！") // ，请取消后再重新选择
    //   return
    // }
    let cartid = e.currentTarget.dataset.cartid;
    this.data.list.forEach((chi, index) => {
      if (chi.id == cartid) {
        this.data.list[index].count += 1
      }
    })
    this.setData({
      list: this.data.list,
      nums: this.data.nums + 1
    })
  },
  get_specification(id){
    return new Promise((resolve,reject)=>{
      app._getNetWork({
        url:app.getNetAddresss("goods.goods.get-goods-page"),
        data:{id:Number(id)},
        success:resdata=>{
          let {result,data} = resdata.data;
          if(result){
            if(data.get_goods.has_many_options && data.get_goods.has_many_options.length!==0){
              resolve(data.get_goods.has_many_options[0].id)
            }else{
              resolve(0)
            }
          }else{
            reject()
          }
        }
      })
    })
  },
  async cart(e) {
    // if (this.data.nums + 1 > this.data.details.exchange_limit) {
    //   app.tips("选择的数量已经超过兑换数量限制！") // ，请取消后再重新选择
    //   return
    // }
    let item = e.currentTarget.dataset.item;
    let nums = 0;
    optionsId = '';
    let option_id =  await this.get_specification(item.id);
    this.data.list.forEach((chi, index) => {
      if (this.data.details.single_order == 1) { //单选
        if (item.id == chi.id) {
          this.data.list[index].count = 1;
          this.data.list[index].option_id = option_id;
        } else {
          this.data.list[index].count = 0;
          this.data.list[index].option_id = option_id;
        }
      } else { //多选
        if (item.id == chi.id) {
          this.data.list[index].count = 1;
          this.data.list[index].option_id = option_id;
        }
      }

    })

    this.data.list.forEach(item_2 => {
      nums += item_2.count
    })

    if (this.data.details.single_order == 1) {
      this.setData({
        specid: '',
        has_many_goods: []
      })
    }
    this.setData({
      list: this.data.list,
      nums
    })
  },

  gotoOrder: function() {
    wx.navigateTo({
      url: '/packageA/member/myOrder_v2/myOrder_v2',
    })
  },

  goShop: function() {
    wx.navigateTo({
      url: '/packageG/pages/category_v2/category_v2',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({showChoose:false})
    if (this.data.option_type == "4"){
      // this.binding_handle_donation()
    }else if (this.data.option_type == "1"){
      this.getCardStatus(this.data.record_id) 
    }else{
      this.getData()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if(this.data.share == 1){
      let {
        title,
        imgUrl,
        description
      } = wx.getStorageSync("wxShareInfo")
      if (title || imgUrl || description) {
        return {
          title: title,
          imageUrl: imgUrl,
          path: '/packageG/gift_card/index/index?id=' + this.data.id + '&code_id=' + this.data.code_id
        }
      }
    }else{
      return {
        title: this.data.details.share_title,
        imageUrl: this.data.details.share_icon,
        path: '/packageG/gift_card/index/index?id=' + this.data.id + '&code_id=' + this.data.code_id
      }
    }
   

  }
})